package com.analyse.stock.job;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.enums.StrategyEnum;
import com.analyse.stock.model.StrategyPoolModel;
import com.analyse.stock.service.IStrategyPoolService;
import com.analyse.stock.strategy.StrategyHandle;
import com.analyse.stock.utils.PublicHolidayUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.Objects;

/**
 * 每日 15.30分后 自动选股
 * 从每天板块净流入资金前5名中选出
 **/
@Component
@Slf4j
public class ScanStockDailyJob implements Job {

    @Autowired
    private StrategyHandle strategyHandle;

    @Autowired
    private IStrategyPoolService strategyPoolService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        boolean isTrading = PublicHolidayUtil.isTradingDateTime("XSHE", DateUtil.date(), localTime->{
            LocalTime time = LocalTime.of(15, 0);
            return localTime.isAfter(time);
        });
        log.info("### 开始 自动选股, 【{}】选股时间 ###",isTrading?"正在":"不在");
        if(!isTrading){
            return;
        }
        long time0 = System.currentTimeMillis();
        StrategyPoolModel strategyModel = strategyPoolService.getStrategyPoolByCode(StrategyEnum.PICK_STOCK.getCode());
        if(Objects.isNull(strategyModel)){
            log.error("对应分析策略类型为空:{}",StrategyEnum.PICK_STOCK.getCode());
            return;
        }
        try {
            strategyHandle.getStrategy(strategyModel.getStrategyCode()).run(strategyModel.getParamJson());
        } catch (Exception ex) {
            log.error("###  执行选股策略，编码:{} ，名称：{} ,参数：{}, error:{}",
                    strategyModel.getStrategyCode(), strategyModel.getStrategyName(), JSONObject.toJSONString(strategyModel), ex.getMessage(),ex);
        }
        log.info("### 结束每日自动从 净流入资金前5名的板块中选出股票已执行完成,耗时：{} 秒 END ###",(System.currentTimeMillis()-time0)/1000);
    }
}
